package com.yifeng.repo.controller.postman.web;

import com.gomcarter.frameworks.base.json.ErrorCode;
import com.yifeng.repo.base.utils.common.BaseUtil;
import com.yifeng.repo.base.utils.servlet.RequestHelper;
import com.yifeng.repo.base.utils.servlet.ResponseHelper;
import com.yifeng.repo.controller.postman.work.PostmanManager;
import com.yifeng.repo.controller.postman.work.dto.HttpRequestParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by daibing on 2023/5/23.
 */
@Slf4j
public class PostmanServlet extends HttpServlet {
    private final PostmanManager postmanManager;

    public PostmanServlet(PostmanManager postmanManager) {
        this.postmanManager = postmanManager;
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpRequestParam callbackParam = new HttpRequestParam();
        callbackParam.setMethod(HttpMethod.resolve(req.getMethod()));
        callbackParam.setContentType(req.getContentType());
        callbackParam.setHeader(RequestHelper.headerMap(req));
        callbackParam.setBody(RequestHelper.body(req.getReader()));
        callbackParam.setUri(req.getRequestURI());
        try {
            String msg = postmanManager.doCallbackWork(callbackParam);
            ResponseHelper.doWrite(resp, msg);
        } catch (Throwable t) {
            log.error("callback handle failed, body={}, error: ", BaseUtil.safeCut(callbackParam.getBody(), 300), t);
            ResponseHelper.doError(resp, ErrorCode.systemInternalError.getCode(), t.getMessage());
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
